package zz.java8.vote.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import bean.Task;
import bean.User;
import dao.JdbcUtil;
import zz.java8.vote.bean.Voters;
//1
public class VotersDao {
	public List findAll() {
		List ls = new ArrayList();
		Voters voter = null;
		Connection con = JdbcUtil.getConnection();
		try {
			String sql = "select * from voter ";
			PreparedStatement ps = con.prepareStatement(sql);			
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				voter = new Voters();
				voter.setId(rs.getInt("id"));
				voter.setName(rs.getString("name"));
				voter.setVoteNum(rs.getInt("vote"));
				ls.add(voter);
			}
			JdbcUtil.closeCon(rs, ps, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return ls;
	}
	
	public boolean updateVote(Voters v) {
		boolean f = false;
		Connection con = JdbcUtil.getConnection();
		try {
			String sql = "update voter set vote=? where id=?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, v.getVoteNum()+1);
			ps.setInt(2, v.getId());
			ps.execute();
			f = true;
			JdbcUtil.closeCon(null, ps, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return f;
	}
	
	public Voters findVoter(int id) {
		Voters voter = null;
		Connection con = JdbcUtil.getConnection();
		try {
			
			String sql = "select * from voter where id=?";
			PreparedStatement ps = con.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				voter = new Voters();
				voter.setId(rs.getInt("id"));
				voter.setName(rs.getString("name"));
				voter.setVoteNum(rs.getInt("vote"));
			}
			JdbcUtil.closeCon(rs, ps, con);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return voter;
	}
}
